package com.custom.common.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.TextCodec;

import java.util.Date;

/**
 * @ClassName: JWTVerifyUtils
 * @description:封装jwt加解密方式
 * @author: liukui
 * @date: 2018/11/17 15:09
 * @version: 1.0
 */
public class JWTVerifyUtils {
    /**
     * 加密方法
     * @param uid
     * @param issue
     * @param jwtSecretKey
     * @param avaliableTime
     * @param bearer
     * @return
     */
    public static String genJWT(String uid, String issue, String jwtSecretKey, Long avaliableTime, String bearer) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + avaliableTime.longValue());
        String authContext = Jwts.builder().setSubject(uid).setIssuer(issue).setIssuedAt(now).setExpiration(expirationDate).setNotBefore(now).signWith(SignatureAlgorithm.HS256, TextCodec.BASE64.encode(jwtSecretKey.getBytes())).compact();
        return bearer + authContext;
    }

    /**
     * 解密方法
     * @param authorization
     * @param jwtSecretKey
     * @return
     */
    public static Claims verifyNotStartWithBearer(String authorization, String jwtSecretKey) {
        String token = authorization;
       // logger.debug("token:" + authorization);
        Claims claims = null;

        try {
            claims = (Claims) Jwts.parser().setSigningKey(TextCodec.BASE64.encode(jwtSecretKey)).parseClaimsJws(token).getBody();
        } catch (SignatureException e) {
            e.getMessage();
            return null;
        } catch (ExpiredJwtException e) {
            e.getMessage();
            return null;
        } catch (PrematureJwtException e) {
            e.getMessage();
            return null;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }

        return claims;
    }
}
